<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/my_blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/my_blog/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/my_blog/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/my_blog/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/my_blog/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/my_blog/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/my_blog/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="#.NET 中的内存管理和垃圾回收机制 (1) - 内存管理 本文参考来源：Memory Management and Garbage Collection in .NET  内存管理 - 清理非托管资源对于应用程序创建的大多数对象，一般情况下可以依靠.NET的垃圾收集器来处理内存管理。 但是，对于包含非托管资源的对象，必须在创建并使用后，显式的释放其中的非托管的资源。 最常见的非托管资源是操作系">
<meta name="keywords" content="CSharp">
<meta property="og:type" content="article">
<meta property="og:title" content="Memory Management and Garbage Collection in .NET - 1">
<meta property="og:url" content="http://sdfsd23few23.gitee.io/my_blog/2018/08/10/DotNet-Guide-Memory-Management/index.html">
<meta property="og:site_name" content="Raymond&#39;s Blog">
<meta property="og:description" content="#.NET 中的内存管理和垃圾回收机制 (1) - 内存管理 本文参考来源：Memory Management and Garbage Collection in .NET  内存管理 - 清理非托管资源对于应用程序创建的大多数对象，一般情况下可以依靠.NET的垃圾收集器来处理内存管理。 但是，对于包含非托管资源的对象，必须在创建并使用后，显式的释放其中的非托管的资源。 最常见的非托管资源是操作系">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-08-10T16:00:16.849Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Memory Management and Garbage Collection in .NET - 1">
<meta name="twitter:description" content="#.NET 中的内存管理和垃圾回收机制 (1) - 内存管理 本文参考来源：Memory Management and Garbage Collection in .NET  内存管理 - 清理非托管资源对于应用程序创建的大多数对象，一般情况下可以依靠.NET的垃圾收集器来处理内存管理。 但是，对于包含非托管资源的对象，必须在创建并使用后，显式的释放其中的非托管的资源。 最常见的非托管资源是操作系">






  <link rel="canonical" href="http://sdfsd23few23.gitee.io/my_blog/2018/08/10/DotNet-Guide-Memory-Management/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Memory Management and Garbage Collection in .NET - 1 | Raymond's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/my_blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Raymond's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">CSharp & Java</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/my_blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Startseite</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/my_blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />Tags</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/my_blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />Kategorien</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/my_blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archiv</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://sdfsd23few23.gitee.io/my_blog/my_blog/2018/08/10/DotNet-Guide-Memory-Management/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Raymond">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/my_blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Raymond's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Memory Management and Garbage Collection in .NET - 1
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Veröffentlicht am</span>
              

              
                
              

              <time title="Post created: 2018-08-10 20:45:33" itemprop="dateCreated datePublished" datetime="2018-08-10T20:45:33+08:00">2018-08-10</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Updated at: 2018-08-11 00:00:16" itemprop="dateModified" datetime="2018-08-11T00:00:16+08:00">2018-08-11</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">in</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/my_blog/categories/Coding/" itemprop="url" rel="index"><span itemprop="name">Coding</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>#.NET 中的内存管理和垃圾回收机制 (1) - 内存管理</p>
<p>本文参考来源：<a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/memory-management-and-gc" target="_blank" rel="noopener">Memory Management and Garbage Collection in .NET</a> </p>
<h2 id="内存管理-清理非托管资源"><a href="#内存管理-清理非托管资源" class="headerlink" title="内存管理 - 清理非托管资源"></a>内存管理 - 清理非托管资源</h2><p>对于应用程序创建的大多数对象，一般情况下可以依靠.NET的垃圾收集器来处理内存管理。 但是，对于包含非托管资源的对象，必须在创建并使用后，<strong>显式</strong>的释放其中的非托管的资源。</p>
<p>最常见的非托管资源是操作系统的资源，例如文件，窗口，网络连接或数据库连接。</p>
<p>虽然垃圾收集器能够跟踪封装非托管资源的对象的生命周期，但它不知道如何释放和清理非托管资源。</p>
<p>对于包含非托管资源的对象，你应当：</p>
<ol>
<li><p>实现 <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern" target="_blank" rel="noopener">dispose pattern</a>：即实现 <a href="https://docs.microsoft.com/en-us/dotnet/api/system.idisposable.dispose" target="_blank" rel="noopener">IDisposable</a> 接口，并在接口中实现对非托管对象的显式释放。当你的类的调用方调用类的Dispose方法时，非托管资源即可立即释放。</p>
</li>
<li><p>当你的类的调用方没有调用Dispose方法时，你需要通过下面两种方法（二选一），释放非托管资源：</p>
<ul>
<li><p>使用 safe handle 来封装非托管资源，这是推荐的方法。 safe handle 派生自 <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.safehandle" target="_blank" rel="noopener">System.Runtime.InteropServices.SafeHandle</a> 类，并包含一个强大的Finalize方法。 当使用 safe handle 时，只需实现 IDisposable 接口并在 IDisposable.Dispose 实现中调用 safe handle 的 Dispose 方法。 如果没有调用 Dispose 方法，则垃圾收集器会自动调用 safe handle 的终结器。</p>
</li>
<li><p>重写 Object.Finalize 方法。 当类型的调用方没有调用 IDisposable.Dispose 时，Finalize 方法可以非确定的释放非托管资源（根据GC）。 但是，由于对象的 Finalize 是一个复杂且容易出错的操作，因此我们建议使用 safe handle 而不是提供自己的 Finalize 方法。</p>
</li>
</ul>
</li>
</ol>
<p>当正确实现Dispose方法时，safe handle 的 Finalize 方法或重写的 Object.Finalize 方法将成为在未调用 Dispose 方法时的安全措施。</p>
<h3 id="实现-Dispose-方法"><a href="#实现-Dispose-方法" class="headerlink" title="实现 Dispose 方法"></a>实现 Dispose 方法</h3><p>实现 Dispose 的两种方法在前面的章节已经介绍过了，需要注意的是为了确保始终适当地清理资源，Dispose方法应该可以多次调用，而不会抛出异常。</p>
<p><strong>注意</strong>：当 Finalize 方法执行时间过长时，在 Dispose 方法结束时调用 GC.KeepAlive() 方法来确保GC回收内存时，Dispose 方法已经执行完毕。</p>
<h4 id="Dispose-和-Dispose-Boolean"><a href="#Dispose-和-Dispose-Boolean" class="headerlink" title="Dispose() 和 Dispose(Boolean)"></a>Dispose() 和 Dispose(Boolean)</h4><p>下面是VS自动实现的 IDispoable 接口：</p>
<pre><code>class Class1 : IDisposable
{

    #region IDisposable Support
    private bool disposedValue = false; // 要检测冗余调用

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: 释放托管状态(托管对象)。
            }

            // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
            // TODO: 将大型字段设置为 null。

            disposedValue = true;
        }
    }

    // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
    // ~Class1() {
    //   // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
    //   Dispose(false); //传递 False 来阻止 Finalize 尝试释放可能已经回收的托管资源
    // }

    // 添加此代码以正确实现可处置模式。
    public void Dispose()
    {
        // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
        Dispose(true);
        // TODO: 如果在以上内容中替代了终结器，则取消注释以下行。
        // GC.SuppressFinalize(this);
    }
    #endregion
}
</code></pre><h4 id="使用-safe-handles"><a href="#使用-safe-handles" class="headerlink" title="使用 safe handles"></a>使用 safe handles</h4><p>Microsoft.Win32.SafeHandles 命名空间提供了一组派生自 SafeHandle 的类。 如果找不到适合的非托管资源的类，你可以实现自己的SafeHandle子类。</p>
<ol>
<li><p>The SafeFileHandle, SafeMemoryMappedFileHandle, and SafePipeHandle class.</p>
</li>
<li><p>The SafeMemoryMappedViewHandle class.</p>
</li>
<li><p>The SafeNCryptKeyHandle, SafeNCryptProviderHandle, and SafeNCryptSecretHandle classes.</p>
</li>
<li><p>The SafeRegistryHandle class.</p>
</li>
<li><p>The SafeWaitHandle class.</p>
</li>
</ol>
<p>以下示例定义了一个 DisposableResource 类，它使用 SafeFileHandle 来包装表示打开文件的 Stream 对象。 DisposableResource 方法还包括一个属性 Size，它返回文件流中的总字节数。</p>
<pre><code>using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.Runtime.InteropServices;

public class DisposableStreamResource : IDisposable
{
    // Define constants.
    protected const uint GENERIC_READ = 0x80000000;
    protected const uint FILE_SHARE_READ = 0x00000001;
    protected const uint OPEN_EXISTING = 3;
    protected const uint FILE_ATTRIBUTE_NORMAL = 0x80;
    protected IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
    private const int INVALID_FILE_SIZE = unchecked((int) 0xFFFFFFFF);

    // Define Windows APIs.
    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;CreateFileW&quot;, CharSet = CharSet.Unicode)]
    protected static extern IntPtr CreateFile (
                                    string lpFileName, uint dwDesiredAccess, 
                                    uint dwShareMode, IntPtr lpSecurityAttributes, 
                                    uint dwCreationDisposition, uint dwFlagsAndAttributes, 
                                    IntPtr hTemplateFile);

    [DllImport(&quot;kernel32.dll&quot;)]
    private static extern int GetFileSize(SafeFileHandle hFile, out int lpFileSizeHigh);

    // Define locals.
    private bool disposed = false;
    private SafeFileHandle safeHandle; 
    private long bufferSize;
    private int upperWord;

    public DisposableStreamResource(string filename)
    {
        if (filename == null)
            throw new ArgumentNullException(&quot;The filename cannot be null.&quot;);
        else if (filename == &quot;&quot;)
            throw new ArgumentException(&quot;The filename cannot be an empty string.&quot;);

        IntPtr handle = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ,
                                    IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
                                    IntPtr.Zero);
        if (handle != INVALID_HANDLE_VALUE)
            safeHandle = new SafeFileHandle(handle, true);
        else
            throw new FileNotFoundException(String.Format(&quot;Cannot open &apos;{0}&apos;&quot;, filename));

        // Get file size.
        bufferSize = GetFileSize(safeHandle, out upperWord); 
        if (bufferSize == INVALID_FILE_SIZE)
            bufferSize = -1;
        else if (upperWord &gt; 0) 
            bufferSize = (((long)upperWord) &lt;&lt; 32) + bufferSize;
    }

    public long Size 
    { get { return bufferSize; } }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }           

    protected virtual void Dispose(bool disposing)
    {
        if (disposed) return;

        // Dispose of managed resources here.
        if (disposing)
            safeHandle.Dispose();

        // Dispose of any unmanaged resources not wrapped in safe handles.

        disposed = true;
    }  
}
</code></pre><h3 id="使用实现了-IDisposable-接口的对象"><a href="#使用实现了-IDisposable-接口的对象" class="headerlink" title="使用实现了 IDisposable 接口的对象"></a>使用实现了 IDisposable 接口的对象</h3><p>当您完成使用实现 IDisposable 的对象时，您应该调用该对象的 Disposable.Dispose 实现。 你可以通过以下两种方式之一完成此操作：</p>
<ol>
<li><p>使用 using 语句。</p>
</li>
<li><p>通过实现 try / finally 块。</p>
</li>
</ol>
<h4 id="using-语句"><a href="#using-语句" class="headerlink" title="using 语句"></a>using 语句</h4><p>C＃ 中的 using 语句简化了必须编写以创建和清理对象的代码。 using 语句获取一个或多个资源，执行您指定的语句，并自动处理该对象。 </p>
<p>但是，using语句仅对在构造它们的方法范围内使用的对象有用。</p>
<p>以下示例使用using语句创建和释放System.IO.StreamReader对象。</p>
<p>using System;<br>using System.IO;</p>
<pre><code>public class Example
{
    public static void Main()
    {
        Char[] buffer = new Char[50];
        using (StreamReader s = new StreamReader(&quot;File1.txt&quot;)) {
            int charsRead = 0;
            while (s.Peek() != -1) {
                charsRead = s.Read(buffer, 0, buffer.Length);
                //
                // Process characters read.
                //   
            }
            s.Close();    
        }

    }
}
</code></pre><p>C＃using 语句还允许您在单个语句中获取多个资源，这在内部等效于嵌套的 using 语句。 以下示例实例化两个 StreamReader 对象以读取两个不同文件的内容。</p>
<p>using System;<br>using System.IO;</p>
<pre><code>public class Example
{
    public static void Main()
    {
        Char[] buffer1 = new Char[50], buffer2 = new Char[50];

        using (StreamReader version1 = new StreamReader(&quot;file1.txt&quot;),
                            version2 = new StreamReader(&quot;file2.txt&quot;)) {
            int charsRead1, charsRead2 = 0;
            while (version1.Peek() != -1 &amp;&amp; version2.Peek() != -1) {
                charsRead1 = version1.Read(buffer1, 0, buffer1.Length);
                charsRead2 = version2.Read(buffer2, 0, buffer2.Length);
                //
                // Process characters read.
                //
            }
            version1.Close();
            version2.Close();
        }
    }
}
</code></pre><h4 id="try-finally-代码块"><a href="#try-finally-代码块" class="headerlink" title="try / finally 代码块"></a>try / finally 代码块</h4><p>当 C＃ 编译器遇到using语句时，它会生成中间语言（IL），它等效于以下显式包含try / finally块的代码。</p>
<pre><code>using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        Char[] buffer = new Char[50];
        {
            StreamReader s = new StreamReader(&quot;File1.txt&quot;); 
            try {
                int charsRead = 0;
                while (s.Peek() != -1) {
                charsRead = s.Read(buffer, 0, buffer.Length);
                //
                // Process characters read.
                //   
                }
                s.Close();
            }
            finally {
                if (s != null)
                ((IDisposable)s).Dispose();     
            }       
        }
    }
}
</code></pre>
      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/my_blog/tags/CSharp/" rel="tag"># CSharp</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/my_blog/2018/06/24/DotNet-Guide-Threading/" rel="next" title="Parallel Processing, Concurrency, and Async Programming in .NET - 1">
                <i class="fa fa-chevron-left"></i> Parallel Processing, Concurrency, and Async Programming in .NET - 1
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/my_blog/2018/08/10/DotNet-Guide-Garbage-Collection/" rel="prev" title="Memory Management and Garbage Collection in .NET - 2">
                Memory Management and Garbage Collection in .NET - 2 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Inhaltsverzeichnis
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Übersicht
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Raymond</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/my_blog/archives/">
                
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">Artikel</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/my_blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">Kategorien</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/my_blog/Tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">11</span>
                    <span class="site-state-item-name">Tags</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#内存管理-清理非托管资源"><span class="nav-number">1.</span> <span class="nav-text">内存管理 - 清理非托管资源</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实现-Dispose-方法"><span class="nav-number">1.1.</span> <span class="nav-text">实现 Dispose 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Dispose-和-Dispose-Boolean"><span class="nav-number">1.1.1.</span> <span class="nav-text">Dispose() 和 Dispose(Boolean)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用-safe-handles"><span class="nav-number">1.1.2.</span> <span class="nav-text">使用 safe handles</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用实现了-IDisposable-接口的对象"><span class="nav-number">1.2.</span> <span class="nav-text">使用实现了 IDisposable 接口的对象</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#using-语句"><span class="nav-number">1.2.1.</span> <span class="nav-text">using 语句</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#try-finally-代码块"><span class="nav-number">1.2.2.</span> <span class="nav-text">try / finally 代码块</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Raymond</span>

  

  
</div>




  <div class="powered-by">Erstellt mit  <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Pisces</a> v6.3.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/my_blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/my_blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/my_blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/my_blog/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/my_blog/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/my_blog/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/my_blog/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/my_blog/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/my_blog/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/my_blog/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
